package com.app.yourradioapp593.activities;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.content.res.AssetManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewStub;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.activity.OnBackPressedCallback;
import androidx.activity.OnBackPressedDispatcher;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.cardview.widget.CardView;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.ColorUtils;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.ProcessLifecycleOwner;
import androidx.palette.graphics.Palette;
import androidx.viewpager.widget.ViewPager;

import com.app.yourradioapp593.BuildConfig;
import com.app.yourradioapp593.Config;
import com.app.yourradioapp593.R;
import com.app.yourradioapp593.database.dao.AppDatabase;
import com.app.yourradioapp593.database.dao.DAO;
import com.app.yourradioapp593.database.dao.RadioEntity;
import com.app.yourradioapp593.database.prefs.AdsPref;
import com.app.yourradioapp593.database.prefs.SharedPref;
import com.app.yourradioapp593.fragments.FragmentCategory;
import com.app.yourradioapp593.fragments.FragmentCategoryDetail;
import com.app.yourradioapp593.fragments.FragmentFavorite;
import com.app.yourradioapp593.fragments.FragmentHome;
import com.app.yourradioapp593.fragments.FragmentRadio;
import com.app.yourradioapp593.fragments.FragmentSearch;
import com.app.yourradioapp593.fragments.FragmentSettings;
import com.app.yourradioapp593.fragments.FragmentSocial;
import com.app.yourradioapp593.models.Radio;
import com.app.yourradioapp593.models.Value;
import com.app.yourradioapp593.rests.ApiInterface;
import com.app.yourradioapp593.rests.RestAdapter;
import com.app.yourradioapp593.services.RadioPlayerService;
import com.app.yourradioapp593.utils.AdsManager;
import com.app.yourradioapp593.utils.AppBarLayoutBehavior;
import com.app.yourradioapp593.utils.Constant;
import com.app.yourradioapp593.utils.NavigationType;
import com.app.yourradioapp593.utils.PaletteUtils;
import com.app.yourradioapp593.utils.RelativePopupWindow;
import com.app.yourradioapp593.utils.RtlViewPager;
import com.app.yourradioapp593.utils.Tools;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.Transition;
import com.google.android.gms.tasks.Task;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.card.MaterialCardView;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.slider.Slider;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.tabs.TabLayout;
import com.google.android.play.core.appupdate.AppUpdateInfo;
import com.google.android.play.core.appupdate.AppUpdateManager;
import com.google.android.play.core.appupdate.AppUpdateManagerFactory;
import com.google.android.play.core.install.model.AppUpdateType;
import com.google.android.play.core.install.model.UpdateAvailability;
import com.google.android.play.core.review.ReviewInfo;
import com.google.android.play.core.review.ReviewManager;
import com.google.android.play.core.review.ReviewManagerFactory;
import com.h6ah4i.android.widget.verticalseekbar.VerticalSeekBar;
import com.solodroid.push.sdk.provider.OneSignalPush;
import com.solodroidx.ads.appopen.AppOpenAd;
import com.sothree.slidinguppanel.SlidingUpPanelLayout;

import java.util.ArrayList;

import es.claucookie.miniequalizerlibrary.EqualizerView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity implements DefaultLifecycleObserver {

    private final static String TAG = "MainActivity";
    SlidingUpPanelLayout slidingUpPanelLayout;
    ProgressBar progressBar, progressBarCollapse;
    SeekBar seekBarSong;
    LinearLayout lytCollapseColor, lytPlayerExpand, lytPlayCollapse;
    LinearLayout lytCollapse;
    RelativeLayout lytDrag;
    RelativeLayout lytExpand, lytSeekBar;
    ImageView imgRadioSmall;
    ImageView imgAlbumArtSmall;

    RelativeLayout lytCoverImagePortrait;
    ImageView imgRadioLargePortrait;
    ImageView imgAlbumArtLargePortrait;

    RelativeLayout lytCoverImageLandscape;
    ImageView imgRadioLargeLandscape;
    ImageView imgAlbumArtLargeLandscape;

    ImageView imgMusicBackground;
    ImageView imgNextExpand, imgPreviousExpand, imgVolume, imgFavorite;
    ImageView imgCollapse, imgTimer, imgTimerStop, imgShare;
    ImageView imgPlay, imgNext, imgPrevious;
    MaterialButton fabPlayExpand;
    TextView txtRadioName, txtMetadata, txtRadioNameExpand, txtMetadataExpand, txtDuration, txtTotalDuration;
    Boolean isExpand = false;
    SharedPref sharedPref;
    Handler seekHandler = new Handler();
    Toolbar toolbar;
    FragmentManager fragmentManager;
    EqualizerView equalizerView;
    View lytMusicScreen;
    CardView lytSearchBar;
    MaterialCardView cardMiniPlayer;
    TextView toolbarTitle;
    Tools tools;
    AdsPref adsPref;
    private DAO db;
    private boolean flagReadLater;
    AppBarLayout appBarLayout;
    AdsManager adsManager;
    private AppUpdateManager appUpdateManager;
    private ViewPager viewPager;
    private RtlViewPager viewPagerRTL;
    CoordinatorLayout parentView;
    View bgLine;
    TextView txtTimer;
    CountDownTimer mCountDownTimer;
    public static long minutes = 1;
    LinearLayout lytBannerAd;
    TabLayout tabLayout;
    RelativeLayout lytBackground;
    RelativeLayout rootView;
    OnBackPressedDispatcher onBackPressedDispatcher;
    boolean isFirstTime = true;

    @SuppressWarnings("ConstantValue")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Tools.getTheme(this);
        sharedPref = new SharedPref(this);
        if (Config.NAVIGATION_TYPE == NavigationType.BOTTOM_NAVIGATION) {
            if (sharedPref.getIsDarkTheme()) {
                setContentView(R.layout.activity_main_navigation_dark);
            } else {
                setContentView(R.layout.activity_main_navigation_light);
            }
        } else {
            setContentView(R.layout.activity_main_tab_layout);
        }
        ViewStub viewStub = findViewById(R.id.app_bar_view_stub);
        if (Config.ENABLE_NEW_UI) {
            viewStub.setLayoutResource(R.layout.include_app_bar);
        } else {
            viewStub.setLayoutResource(R.layout.include_app_bar_legacy);
        }
        viewStub.inflate();

//        if (Config.NAVIGATION_TYPE == NavigationType.BOTTOM_NAVIGATION) {
//            Tools.setMainNavigation(this);
//        } else {
        Tools.setNavigation(this);
//        }
        db = AppDatabase.getDb(this).get();
        adsPref = new AdsPref(this);
        tools = new Tools(this);

        if (Config.FORCE_TO_SHOW_APP_OPEN_AD_ON_START) {
            ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
            adsPref.setIsOpenAd(true);
        }

        appBarLayout = findViewById(R.id.tab_appbar_layout);
        ((CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams()).setBehavior(new AppBarLayoutBehavior());

        adsManager = new AdsManager(this);

        Tools.postDelayed(() -> {
            adsManager.initializeAd();
            adsManager.updateConsentStatus();
            adsManager.loadAppOpenAd(Config.APP_OPEN_AD_ON_RESUME, false, () -> {
            });
            adsManager.loadBannerAd(Config.BANNER_HOME);
            adsManager.loadInterstitialAd(Config.INTERSTITIAL_RADIO_LIST, adsPref.getInterstitialAdInterval());
        }, 100);

        Constant.is_app_open = true;

        initComponent();
        setupToolbar();

        setupTabLayout();
        setupViewPager(viewPager, viewPagerRTL);

        themeColor();
        Tools.notificationOpenHandler(this, getIntent());

        if (!BuildConfig.DEBUG) {
            appUpdateManager = AppUpdateManagerFactory.create(getApplicationContext());
            inAppUpdate();
            inAppReview();
        }

        new OneSignalPush.Builder(this).requestPushNotificationPermission();

        handleOnBackPressed();

        isPortrait(getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE);

    }

    @Override
    public void onStart(@NonNull LifecycleOwner owner) {
        DefaultLifecycleObserver.super.onStart(owner);
        Tools.postDelayed(() -> {
            if (Config.APP_OPEN_AD_ON_RESUME) {
                if (AppOpenAd.isAppOpenAdLoaded) {
                    adsManager.showAppOpenAd(() -> {

                    });
                    Log.d(AppOpenAd.TAG, "lifecycleObserver Show App Open Ad");

                }
            }
        }, 100);
    }

    public void showInterstitialAd() {
        adsManager.showInterstitialAd();
    }

    public void setupToolbar() {
        lytSearchBar = findViewById(R.id.lyt_search_bar);
        appBarLayout = findViewById(R.id.tab_appbar_layout);
        toolbar = findViewById(R.id.toolbar);
        toolbarTitle = findViewById(R.id.toolbar_title);
        toolbarTitle.setText(getString(R.string.app_name));

        if (sharedPref.getIsDarkTheme()) {
            lytSearchBar.setCardBackgroundColor(ContextCompat.getColor(this, R.color.color_dark_search_bar));
            toolbarTitle.setTextColor(ContextCompat.getColor(this, R.color.color_white));
            appBarLayout.setBackgroundColor(ContextCompat.getColor(this, R.color.color_dark_background));
            toolbar.setBackgroundColor(ContextCompat.getColor(this, R.color.color_dark_search_bar));
            toolbar.getContext().setTheme(com.google.android.material.R.style.Base_ThemeOverlay_AppCompat_Dark_ActionBar);
            lytBannerAd.setBackgroundColor(ContextCompat.getColor(this, R.color.color_dark_background));
        } else {
            if (Config.ENABLE_NEW_UI) {
                lytSearchBar.setCardBackgroundColor(ContextCompat.getColor(this, R.color.color_light_search_bar));
                toolbarTitle.setTextColor(ContextCompat.getColor(this, R.color.color_light_text));
                appBarLayout.setBackgroundColor(ContextCompat.getColor(this, R.color.color_light_background));
                toolbar.setBackgroundColor(ContextCompat.getColor(this, R.color.color_light_search_bar));
                toolbar.getContext().setTheme(com.google.android.material.R.style.ThemeOverlay_AppCompat_Light);
            } else {
                rootView.setBackgroundColor(ContextCompat.getColor(this, R.color.color_light_status_bar));
                lytSearchBar.setCardBackgroundColor(ContextCompat.getColor(this, R.color.color_light_primary));
                toolbarTitle.setTextColor(ContextCompat.getColor(this, R.color.color_white));
                appBarLayout.setBackgroundColor(ContextCompat.getColor(this, R.color.color_light_primary));
                toolbar.setBackgroundColor(ContextCompat.getColor(this, R.color.color_light_primary));
                toolbar.getContext().setTheme(com.google.android.material.R.style.ThemeOverlay_AppCompat_Light);
            }
            lytBannerAd.setBackgroundColor(ContextCompat.getColor(this, R.color.color_light_background));
        }

        setSupportActionBar(toolbar);
    }

    public void initComponent() {

        fragmentManager = getSupportFragmentManager();
        slidingUpPanelLayout = findViewById(R.id.sliding_layout);

        rootView = findViewById(R.id.root_view);
        lytBackground = findViewById(R.id.lyt_background);

        lytMusicScreen = findViewById(R.id.layout_music_player);
        imgMusicBackground = findViewById(R.id.img_music_background);
        cardMiniPlayer = findViewById(R.id.card_mini_player);

        tabLayout = findViewById(R.id.tab_layout);
        viewPager = findViewById(R.id.view_pager);
        viewPagerRTL = findViewById(R.id.view_pager_rtl);

        equalizerView = findViewById(R.id.equalizer_view);
        progressBar = findViewById(R.id.progress_bar);
        progressBarCollapse = findViewById(R.id.progress_bar_collapse);
        seekBarSong = findViewById(R.id.seek_bar_song);
        imgShare = findViewById(R.id.img_share);

        imgTimer = findViewById(R.id.img_timer);
        txtTimer = findViewById(R.id.txt_timer);
        imgTimerStop = findViewById(R.id.img_timer_stop);

        imgRadioSmall = findViewById(R.id.img_radio_small);
        imgAlbumArtSmall = findViewById(R.id.img_album_art_small);

        lytCoverImagePortrait = findViewById(R.id.lyt_cover_image_portrait);
        imgRadioLargePortrait = findViewById(R.id.img_radio_large_portrait);
        imgAlbumArtLargePortrait = findViewById(R.id.img_album_art_large_portrait);

        lytCoverImageLandscape = findViewById(R.id.lyt_cover_image_landscape);
        imgRadioLargeLandscape = findViewById(R.id.img_radio_large_landscape);
        imgAlbumArtLargeLandscape = findViewById(R.id.img_album_art_large_landscape);

        imgPrevious = findViewById(R.id.img_player_previous);
        imgPreviousExpand = findViewById(R.id.img_previous_expand);
        imgNext = findViewById(R.id.img_player_next);
        imgNextExpand = findViewById(R.id.img_next_expand);
        imgPlay = findViewById(R.id.img_player_play);
        imgFavorite = findViewById(R.id.img_favorite);
        imgVolume = findViewById(R.id.img_volume);
        imgCollapse = findViewById(R.id.img_collapse);
        txtRadioName = findViewById(R.id.txt_radio_name);

        txtMetadata = findViewById(R.id.txt_metadata);
        txtMetadata.setSelected(true);

        fabPlayExpand = findViewById(R.id.fab_play);
        txtRadioNameExpand = findViewById(R.id.txt_radio_name_expand);

        txtMetadataExpand = findViewById(R.id.txt_metadata_expand);
        txtMetadataExpand.setSelected(true);

        txtDuration = findViewById(R.id.txt_song_duration);
        txtTotalDuration = findViewById(R.id.txt_total_duration);

        lytPlayerExpand = findViewById(R.id.lyt_player_expand);
        lytPlayCollapse = findViewById(R.id.lyt_play_collapse);
        lytSeekBar = findViewById(R.id.lyt_song_seek_bar);
        lytCollapse = findViewById(R.id.lyt_collapse);
        lytCollapseColor = findViewById(R.id.lyt_collapse_color);
        lytExpand = findViewById(R.id.lyt_expand);
        lytDrag = findViewById(R.id.lyt_drag);

        bgLine = findViewById(R.id.bg_line);
        parentView = findViewById(R.id.coordinator_layout);
        lytBannerAd = findViewById(R.id.lyt_banner_ad);

        if (!Tools.isNetworkAvailable(this)) {
            txtRadioName.setText(getResources().getString(R.string.app_name));
            txtRadioNameExpand.setText(getResources().getString(R.string.app_name));
            txtMetadata.setText(getResources().getString(R.string.internet_not_connected));
            txtMetadataExpand.setText(getResources().getString(R.string.internet_not_connected));
            lytSeekBar.setVisibility(View.GONE);
        }

        setIfPlaying();

        seekBarSong.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                int progress = seekBar.getProgress();
                try {
                    Constant.exoPlayer.seekTo((int) Tools.getSeekFromPercentage(progress, Constant.exoPlayer.getDuration()));
                } catch (Exception e) {
                    Log.d(TAG, "printStackTrace error: " + e.getMessage());
                    //e.printStackTrace();
                }
            }
        });

        lytCollapse.setOnClickListener(v -> slidingUpPanelLayout.setPanelState(SlidingUpPanelLayout.PanelState.EXPANDED));

        lytExpand.setOnClickListener(v -> {

        });

        slidingUpPanelLayout.setDragView(lytDrag);

        slidingUpPanelLayout.setShadowHeight(0);
        slidingUpPanelLayout.addPanelSlideListener(new SlidingUpPanelLayout.PanelSlideListener() {
            @Override
            public void onPanelSlide(View panel, float slideOffset) {
                if (slideOffset == 0.0f) {
                    isExpand = false;
                    lytExpand.setVisibility(View.GONE);
                } else if (slideOffset > 0.0f && slideOffset < 1.0f) {
                    if (isExpand) {
                        lytCollapse.setVisibility(View.VISIBLE);
                        showBottomNavigation(true);
                        lytExpand.setAlpha(slideOffset);
                    } else {
                        lytExpand.setVisibility(View.VISIBLE);
                        lytExpand.setAlpha(0.0f + slideOffset);
                    }
                    lytCollapse.setAlpha(1.0f - slideOffset);
                    tabLayout.setAlpha(1.0f - slideOffset);
                } else {
                    isExpand = true;
                    lytCollapse.setVisibility(View.GONE);
                    showBottomNavigation(false);
                }
            }

            @Override
            public void onPanelStateChanged(View panel, SlidingUpPanelLayout.PanelState previousState, SlidingUpPanelLayout.PanelState newState) {
                if (newState == SlidingUpPanelLayout.PanelState.EXPANDED) {
                    lytExpand.setVisibility(View.VISIBLE);
                    lytCollapse.setVisibility(View.GONE);
                    showBottomNavigation(false);
                    changePlayerBackground(Constant.colorBitmap, true);
                    Constant.isPlayerExpanded = true;
                    if (!Constant.item_radio.isEmpty()) {
                        changeFav(Constant.item_radio.get(Constant.position));
                        if (!sharedPref.getIsDarkTheme()) {
                            Tools.windowLightStatusBar(MainActivity.this, false);
                        }
                    }
                    Log.d(TAG, "expanded");
                }
                if (newState == SlidingUpPanelLayout.PanelState.COLLAPSED) {
                    lytExpand.setVisibility(View.GONE);
                    lytCollapse.setVisibility(View.VISIBLE);
                    showBottomNavigation(true);
                    if (sharedPref.getIsDarkTheme()) {
                        Tools.darkNavigation(MainActivity.this);
                        Tools.setStatusBarColor(MainActivity.this, rootView, ContextCompat.getColor(MainActivity.this, R.color.color_dark_status_bar));
                        Tools.windowLightStatusBar(MainActivity.this, false);
                    } else {
                        Tools.lightNavigation(MainActivity.this);
                        if (Config.ENABLE_NEW_UI) {
                            Tools.setStatusBarColor(MainActivity.this, rootView, ContextCompat.getColor(MainActivity.this, R.color.color_white));
                        } else {
                            Tools.setStatusBarColor(MainActivity.this, rootView, ContextCompat.getColor(MainActivity.this, R.color.color_light_status_bar));
                        }
                        Tools.windowLightStatusBar(MainActivity.this, true);
                    }
                    Constant.isPlayerExpanded = false;
                    Log.d(TAG, "collapsed");
                }
            }
        });

        imgPlay.setOnClickListener(view -> {
            if (!Tools.isNetworkAvailable(this)) {
                showSnackBar(getString(R.string.internet_not_connected));
            } else {
                clickPlay(Constant.position);
            }
        });

        fabPlayExpand.setOnClickListener(view -> {
            if (!Tools.isNetworkAvailable(this)) {
                showSnackBar(getString(R.string.internet_not_connected));
            } else {
                clickPlay(Constant.position);
            }
        });

        imgNext.setOnClickListener(view -> togglePlayPosition(true));
        imgNextExpand.setOnClickListener(view -> togglePlayPosition(true));

        imgPrevious.setOnClickListener(view -> togglePlayPosition(false));
        imgPreviousExpand.setOnClickListener(view -> togglePlayPosition(false));

        imgTimer.setOnClickListener(v -> {
            showBannerAd(false);
            View view = getLayoutInflater().inflate(R.layout.dialog_timer, null);

            TextView txtMinutes = view.findViewById(R.id.txt_minutes);
            txtMinutes.setText(minutes + " " + getString(R.string.min));

            Slider seekBar = view.findViewById(R.id.seek_bar_timer);
            seekBar.setValueFrom(1);
            seekBar.setValueTo(180);
            seekBar.setValue(minutes);
            seekBar.addOnChangeListener((slider, value, fromUser) -> {
                int min = (int) value;
                txtMinutes.setText(min + " " + getString(R.string.min));
                minutes = min;
            });

            final MaterialAlertDialogBuilder alert = new MaterialAlertDialogBuilder(this);
            alert.setView(view);
            AlertDialog alertDialog = alert.create();
            Tools.dialogButtonSelected(this, view, alertDialog, () -> startTimer(minutes));

            alertDialog.setOnDismissListener(dialogInterface -> showBannerAd(true));
            alertDialog.show();
        });

        imgTimerStop.setOnClickListener(v -> stopTimer());

        imgShare.setOnClickListener(v -> {
            if (!Constant.item_radio.isEmpty()) {
                Intent share = new Intent(Intent.ACTION_SEND);
                share.setType("text/plain");
                share.putExtra(Intent.EXTRA_TEXT, getString(R.string.share_radio_text) + " - " + Constant.item_radio.get(Constant.position).radio_name + "\n" + getString(R.string.app_name) + " - http://play.google.com/store/apps/details?id=" + getPackageName());
                startActivity(share);
            }
        });

        imgCollapse.setOnClickListener(v -> slidingUpPanelLayout.setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED));

        imgVolume.setOnClickListener(v -> changeVolume());

        imgFavorite.setOnClickListener(view -> {
            if (Tools.isNetworkAvailable(this)) {
                Radio radio = Constant.item_radio.get(Constant.position);
                String radio_id = Constant.item_radio.get(Constant.position).radio_id;
                flagReadLater = db.getRadio(radio_id) != null;
                if (flagReadLater) {
                    db.deleteRadio(radio_id);
                    imgFavorite.setImageDrawable(ContextCompat.getDrawable(MainActivity.this, R.drawable.ic_star_outline));
                    showSnackBar(getString(R.string.favorite_removed));
                } else {
                    db.insertRadio(RadioEntity.entity(radio));
                    imgFavorite.setImageDrawable(ContextCompat.getDrawable(MainActivity.this, R.drawable.ic_star_white));
                    showSnackBar(getString(R.string.favorite_added));
                }
                FragmentFavorite.GetInstance().displayData(db.getAllRadio());
            }
        });

    }

    @SuppressWarnings("ConstantValue")
    public void setupTabLayout() {
        tabLayout.post(() -> {
            rootView.setVisibility(View.VISIBLE);
            if (Config.ENABLE_RTL_MODE) {
                tabLayout.setupWithViewPager(viewPagerRTL);
            } else {
                tabLayout.setupWithViewPager(viewPager);
            }
            if (Config.NAVIGATION_TYPE == NavigationType.TAB_LAYOUT_WITH_ICON) {
                showTabIcons(true);
                tabLayout.setTabMode(TabLayout.MODE_FIXED);
            } else if (Config.NAVIGATION_TYPE == NavigationType.TAB_LAYOUT_WITH_TEXT) {
                showTabIcons(false);
                if (Config.SIMPLE_MODE || !Config.DISPLAY_SOCIAL_IN_NAVIGATION_MENU) {
                    tabLayout.setTabMode(TabLayout.MODE_FIXED);
                } else {
                    tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
                }
            } else if (Config.NAVIGATION_TYPE == NavigationType.TAB_LAYOUT_WITH_ICON_AND_TEXT) {
                showTabIcons(true);
                if (Config.SIMPLE_MODE || !Config.DISPLAY_SOCIAL_IN_NAVIGATION_MENU) {
                    tabLayout.setTabMode(TabLayout.MODE_FIXED);
                } else {
                    tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
                }
            } else {
                showTabIcons(true);
                tabLayout.setTabMode(TabLayout.MODE_FIXED);
            }
        });

        if (sharedPref.getIsDarkTheme()) {
            if (Config.ENABLE_NEW_UI) {
                tabLayout.setBackgroundColor(ContextCompat.getColor(this, R.color.color_dark_background));
            } else {
                tabLayout.setBackgroundColor(ContextCompat.getColor(this, R.color.color_dark_bottom_navigation));
            }
        } else {
            if (Config.ENABLE_NEW_UI) {
                tabLayout.setBackgroundColor(ContextCompat.getColor(this, R.color.color_light_background));
            } else {
                if (Config.NAVIGATION_TYPE == NavigationType.BOTTOM_NAVIGATION) {
                    tabLayout.setBackgroundColor(ContextCompat.getColor(this, R.color.color_light_bottom_navigation));
                } else {
                    tabLayout.setBackgroundColor(ContextCompat.getColor(this, R.color.color_light_primary));
                }
            }
        }
    }

    int[] tabIconsUnselected;
    int[] tabIconsSelected;

    @SuppressWarnings({"DataFlowIssue", "ConstantValue"})
    private void showTabIcons(boolean show) {
        if (show) {
            if (Config.SIMPLE_MODE) {
                tabIconsUnselected = new int[]{R.drawable.ic_nav_explore_unselected, R.drawable.ic_nav_category_unselected, R.drawable.ic_nav_favorite_unselected, R.drawable.ic_nav_social_unselected};
                tabIconsSelected = new int[]{R.drawable.ic_nav_explore_selected, R.drawable.ic_nav_category_selected, R.drawable.ic_nav_favorite_selected, R.drawable.ic_nav_social_selected};
            } else {
                tabIconsUnselected = new int[]{R.drawable.ic_nav_home_unselected, R.drawable.ic_nav_explore_unselected, R.drawable.ic_nav_category_unselected, R.drawable.ic_nav_favorite_unselected, R.drawable.ic_nav_social_unselected};
                tabIconsSelected = new int[]{R.drawable.ic_nav_home_selected, R.drawable.ic_nav_explore_selected, R.drawable.ic_nav_category_selected, R.drawable.ic_nav_favorite_selected, R.drawable.ic_nav_social_selected};
            }
            for (int i = 0; i < tabLayout.getTabCount(); i++) {
                if (tabLayout.getTabAt(i) != null) {
                    if (i == 0) {
                        tabLayout.getTabAt(0).setIcon(tabIconsSelected[0]);
                    } else {
                        tabLayout.getTabAt(i).setIcon(tabIconsUnselected[i]);
                    }

                    if (sharedPref.getIsDarkTheme()) {
                        tabLayout.getTabAt(0).getIcon().setColorFilter(ContextCompat.getColor(MainActivity.this, R.color.color_white), PorterDuff.Mode.SRC_IN);
                    } else {
                        if (!Config.ENABLE_NEW_UI) {
                            if (Config.NAVIGATION_TYPE != NavigationType.BOTTOM_NAVIGATION) {
                                if (i == 0) {
                                    tabLayout.getTabAt(0).getIcon().setColorFilter(ContextCompat.getColor(MainActivity.this, R.color.color_white), PorterDuff.Mode.SRC_IN);
                                } else {
                                    tabLayout.getTabAt(i).getIcon().setColorFilter(ContextCompat.getColor(MainActivity.this, R.color.color_dark_tab_icon_unselected), PorterDuff.Mode.SRC_IN);
                                }
                            }
                        }
                    }
                }
            }
            tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {

                @SuppressWarnings("ConstantValue")
                @Override
                public void onTabSelected(TabLayout.Tab tab) {
                    tab.setIcon(tabIconsSelected[tab.getPosition()]);
                    if (sharedPref.getIsDarkTheme()) {
                        tab.getIcon().setColorFilter(ContextCompat.getColor(MainActivity.this, R.color.color_white), PorterDuff.Mode.SRC_IN);
                    } else {
                        if (!Config.ENABLE_NEW_UI) {
                            if (Config.NAVIGATION_TYPE != NavigationType.BOTTOM_NAVIGATION) {
                                tab.getIcon().setColorFilter(ContextCompat.getColor(MainActivity.this, R.color.color_white), PorterDuff.Mode.SRC_IN);
                            }
                        }
                    }

                    if (Config.NAVIGATION_TYPE == NavigationType.TAB_LAYOUT_WITH_ICON) {
                        if (Config.SIMPLE_MODE) {
                            if (tab.getPosition() == 1) {
                                toolbarTitle.setText(getString(R.string.title_nav_category));
                            } else if (tab.getPosition() == 2) {
                                toolbarTitle.setText(getString(R.string.title_nav_favorite));
                            } else if (tab.getPosition() == 3) {
                                toolbarTitle.setText(getString(R.string.title_nav_social));
                            } else {
                                toolbarTitle.setText(getString(R.string.app_name));
                            }
                        } else {
                            if (tab.getPosition() == 1) {
                                toolbarTitle.setText(getString(R.string.title_nav_explore));
                            } else if (tab.getPosition() == 2) {
                                toolbarTitle.setText(getString(R.string.title_nav_category));
                            } else if (tab.getPosition() == 3) {
                                toolbarTitle.setText(getString(R.string.title_nav_favorite));
                            } else if (tab.getPosition() == 4) {
                                toolbarTitle.setText(getString(R.string.title_nav_social));
                            } else {
                                toolbarTitle.setText(getString(R.string.app_name));
                            }
                        }
                    }
                }

                @Override
                public void onTabUnselected(TabLayout.Tab tab) {
                    tab.setIcon(tabIconsUnselected[tab.getPosition()]);
                    if (sharedPref.getIsDarkTheme()) {
                        tab.getIcon().setColorFilter(ContextCompat.getColor(MainActivity.this, R.color.color_dark_tab_icon_unselected), PorterDuff.Mode.SRC_IN);
                    } else {
                        if (!Config.ENABLE_NEW_UI) {
                            if (Config.NAVIGATION_TYPE != NavigationType.BOTTOM_NAVIGATION) {
                                tab.getIcon().setColorFilter(ContextCompat.getColor(MainActivity.this, R.color.color_dark_tab_icon_unselected), PorterDuff.Mode.SRC_IN);
                            }
                        }
                    }
                }

                @Override
                public void onTabReselected(TabLayout.Tab tab) {

                }
            });

            if (sharedPref.getIsDarkTheme()) {
                tabLayout.setSelectedTabIndicatorColor(ContextCompat.getColor(this, R.color.color_white));
                tabLayout.setTabTextColors(ContextCompat.getColor(this, R.color.color_dark_tab_icon_unselected), ContextCompat.getColor(this, R.color.color_white));
            } else {
                if (!Config.ENABLE_NEW_UI) {
                    if (Config.NAVIGATION_TYPE != NavigationType.BOTTOM_NAVIGATION) {
                        tabLayout.setSelectedTabIndicatorColor(ContextCompat.getColor(this, R.color.color_default_tab_indicator_color));
                        tabLayout.setTabTextColors(ContextCompat.getColor(this, R.color.color_dark_tab_icon_unselected), ContextCompat.getColor(this, R.color.color_white));
                    }
                }
            }
        }
    }

    @SuppressWarnings("ConstantValue")
    private void setupViewPager(ViewPager viewPager, RtlViewPager viewPagerRTL) {
        Tools.ViewPagerAdapter adapter = new Tools.ViewPagerAdapter(getSupportFragmentManager());
        if (Config.SIMPLE_MODE) {
            if (Config.NAVIGATION_TYPE == NavigationType.TAB_LAYOUT_WITH_ICON) {
                adapter.addFrag(new FragmentRadio(), "");
                adapter.addFrag(new FragmentCategory(), "");
                adapter.addFrag(new FragmentFavorite(), "");
                if (Config.DISPLAY_SOCIAL_IN_NAVIGATION_MENU) {
                    adapter.addFrag(new FragmentSocial(), "");
                }
            } else {
                adapter.addFrag(new FragmentRadio(), getString(R.string.title_nav_explore));
                adapter.addFrag(new FragmentCategory(), getString(R.string.title_nav_category));
                adapter.addFrag(new FragmentFavorite(), getString(R.string.title_nav_favorite));
                if (Config.DISPLAY_SOCIAL_IN_NAVIGATION_MENU) {
                    adapter.addFrag(new FragmentSocial(), getString(R.string.title_nav_social));
                }
            }
        } else {
            if (Config.NAVIGATION_TYPE == NavigationType.TAB_LAYOUT_WITH_ICON) {
                adapter.addFrag(new FragmentHome(), "");
                adapter.addFrag(new FragmentRadio(), "");
                adapter.addFrag(new FragmentCategory(), "");
                adapter.addFrag(new FragmentFavorite(), "");
                if (Config.DISPLAY_SOCIAL_IN_NAVIGATION_MENU) {
                    adapter.addFrag(new FragmentSocial(), "");
                }
            } else {
                adapter.addFrag(new FragmentHome(), getString(R.string.title_nav_home));
                adapter.addFrag(new FragmentRadio(), getString(R.string.title_nav_explore));
                adapter.addFrag(new FragmentCategory(), getString(R.string.title_nav_category));
                adapter.addFrag(new FragmentFavorite(), getString(R.string.title_nav_favorite));
                if (Config.DISPLAY_SOCIAL_IN_NAVIGATION_MENU) {
                    adapter.addFrag(new FragmentSocial(), getString(R.string.title_nav_social));
                }
            }
        }
        if (Config.ENABLE_RTL_MODE) {
            viewPagerRTL.setAdapter(adapter);
            viewPagerRTL.setOffscreenPageLimit(adapter.getCount());
            viewPagerRTL.setVisibility(View.VISIBLE);
        } else {
            viewPager.setAdapter(adapter);
            viewPager.setOffscreenPageLimit(adapter.getCount());
            viewPager.setVisibility(View.VISIBLE);
        }
    }

    private void togglePlayPosition(Boolean isNext) {
        if (!Constant.item_radio.isEmpty()) {
            if (RadioPlayerService.getInstance() == null) {
                RadioPlayerService.createInstance().initializeRadio(MainActivity.this, Constant.item_radio.get(Constant.position));
            }
            Intent intent;
            intent = new Intent(MainActivity.this, RadioPlayerService.class);
            if (isNext) {
                intent.setAction(RadioPlayerService.ACTION_NEXT);
            } else {
                intent.setAction(RadioPlayerService.ACTION_PREVIOUS);
            }
            startService(intent);
        }
    }

    public void clickPlay(int position) {
        Constant.position = position;
        if (Constant.item_radio != null) {
            if (!Constant.item_radio.isEmpty()) {
                Radio radio = Constant.item_radio.get(Constant.position);
                final Intent intent = new Intent(MainActivity.this, RadioPlayerService.class);
                if (RadioPlayerService.getInstance() != null) {
                    Radio playerCurrentRadio = RadioPlayerService.getInstance().getPlayingRadioStation();
                    if (playerCurrentRadio != null) {
                        if (!radio.radio_id.equals(RadioPlayerService.getInstance().getPlayingRadioStation().radio_id)) {
                            RadioPlayerService.getInstance().initializeRadio(MainActivity.this, radio);
                            intent.setAction(RadioPlayerService.ACTION_PLAY);
                        } else {
                            intent.setAction(RadioPlayerService.ACTION_TOGGLE);
                        }
                    } else {
                        RadioPlayerService.getInstance().initializeRadio(MainActivity.this, radio);
                        intent.setAction(RadioPlayerService.ACTION_PLAY);
                    }
                } else {
                    RadioPlayerService.createInstance().initializeRadio(MainActivity.this, radio);
                    intent.setAction(RadioPlayerService.ACTION_PLAY);
                }
                startService(intent);
            }
        }
    }

    public void changePlayPause(Boolean flag) {
        Constant.is_playing = flag;
        if (flag) {
            Radio radio = RadioPlayerService.getInstance().getPlayingRadioStation();
            if (radio != null) {
                changeText(radio);
                changeFav(radio);
                imgPlay.setImageDrawable(ContextCompat.getDrawable(MainActivity.this, R.drawable.ic_action_pause));
                fabPlayExpand.setIcon(ContextCompat.getDrawable(MainActivity.this, R.drawable.ic_action_pause));
                equalizerView.animateBars();
            }
        } else {
            if (!Constant.item_radio.isEmpty()) {
                changeText(Constant.item_radio.get(Constant.position));
                changeFav(Constant.item_radio.get(Constant.position));
            }
            imgPlay.setImageDrawable(ContextCompat.getDrawable(MainActivity.this, R.drawable.ic_action_play));
            fabPlayExpand.setIcon(ContextCompat.getDrawable(MainActivity.this, R.drawable.ic_action_play));
            equalizerView.stopBars();
            imgAlbumArtSmall.setVisibility(View.GONE);
            imgAlbumArtLargePortrait.setVisibility(View.GONE);
            imgAlbumArtLargeLandscape.setVisibility(View.GONE);
        }
    }

    public void changeFav(Radio radio) {
        checkFav(radio.radio_id);
    }

    private void checkFav(String id) {
        flagReadLater = db.getRadio(id) != null;
        if (flagReadLater) {
            imgFavorite.setImageDrawable(ContextCompat.getDrawable(MainActivity.this, R.drawable.ic_star_white));
        } else {
            imgFavorite.setImageDrawable(ContextCompat.getDrawable(MainActivity.this, R.drawable.ic_star_outline));
        }
    }

    public void showImageAlbumArt(boolean show) {
        if (show) {
            imgAlbumArtSmall.setVisibility(View.VISIBLE);
            imgAlbumArtLargePortrait.setVisibility(View.VISIBLE);
            imgAlbumArtLargeLandscape.setVisibility(View.VISIBLE);
        } else {
            imgAlbumArtSmall.setVisibility(View.GONE);
            imgAlbumArtLargePortrait.setVisibility(View.GONE);
            imgAlbumArtLargeLandscape.setVisibility(View.GONE);
        }
    }

    public void changeText(Radio radio) {
        if (Constant.radio_type) {
            changeSongName(Constant.metadata);
            if (Constant.metadata == null || Constant.metadata.equals(radio.category_name)) {
                imgAlbumArtSmall.setVisibility(View.GONE);
                imgAlbumArtLargePortrait.setVisibility(View.GONE);
                imgAlbumArtLargeLandscape.setVisibility(View.GONE);
            } else {
                imgAlbumArtSmall.setVisibility(View.VISIBLE);
                imgAlbumArtLargePortrait.setVisibility(View.VISIBLE);
                imgAlbumArtLargeLandscape.setVisibility(View.VISIBLE);
            }
            txtMetadataExpand.setVisibility(View.VISIBLE);
            lytSeekBar.setVisibility(View.GONE);
        } else {
            txtMetadata.setText(radio.category_name);
            txtMetadataExpand.setText(radio.category_name);
            txtMetadataExpand.setVisibility(View.VISIBLE);
            lytSeekBar.setVisibility(View.VISIBLE);
            showImageAlbumArt(false);
        }

        txtRadioName.setText(radio.radio_name);
        txtRadioNameExpand.setText(radio.radio_name);

        if (!Constant.is_playing) {
            txtMetadata.setText(radio.category_name);
            txtMetadataExpand.setText(radio.category_name);
        }

        Glide.with(getApplicationContext())
                .asBitmap()
                .load(sharedPref.getBaseUrl() + "/upload/" + radio.radio_image.replace(" ", "%20"))
                .placeholder(R.drawable.ic_artwork)
                .into(new CustomTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap bitmap, @Nullable Transition<? super Bitmap> transition) {
                        imgRadioSmall.setImageBitmap(bitmap);
                        imgRadioLargePortrait.setImageBitmap(bitmap);
                        imgRadioLargeLandscape.setImageBitmap(bitmap);
                        showBlurBackgroundImage(bitmap);

                        DisplayMetrics displayMetrics = new DisplayMetrics();
                        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
                        Bitmap newBitmap = PaletteUtils.getDominantGradient(bitmap, displayMetrics.heightPixels, displayMetrics.widthPixels);
                        changePlayerBackground(newBitmap, Constant.isPlayerExpanded);
                        Constant.colorBitmap = newBitmap;
                    }

                    @Override
                    public void onLoadCleared(@Nullable Drawable placeholder) {

                    }
                });

    }

    public void showBlurBackgroundImage(Bitmap bitmap) {
        RelativeLayout lytBlurImage = findViewById(R.id.lyt_background_blur);
        if (Config.DISPLAY_RADIO_BACKGROUND_BLUR_IMAGE) {
            ImageView imgRadioBlur = findViewById(R.id.img_music_background_blur);
            Bitmap blurImage = Tools.blurImage(MainActivity.this, bitmap);
            imgRadioBlur.setImageBitmap(blurImage);
            lytBlurImage.setVisibility(View.VISIBLE);
        } else {
            lytBlurImage.setVisibility(View.GONE);
        }
    }

    public void changePlayerBackground(Bitmap bitmap, boolean changeStatusBarColor) {
        if (sharedPref.getIsDarkTheme()) {
            imgMusicBackground.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.color_dark_background));
            if (changeStatusBarColor) {
                if (Config.DISPLAY_RADIO_BACKGROUND_BLUR_IMAGE) {
                    if (bitmap != null) {
                        Palette.from(bitmap).generate(palette -> {
                            int defaultColor = ContextCompat.getColor(this, R.color.color_dark_background);
                            assert palette != null;
                            int color = palette.getDominantColor(defaultColor);
                            int newColor = ColorUtils.blendARGB(color, Color.BLACK, 0.5f);
                            imgMusicBackground.setBackgroundColor(newColor);
                            Tools.setStatusBarColor(MainActivity.this, rootView, newColor);
                        });
                    }
                } else {
                    Tools.setStatusBarColor(MainActivity.this, rootView, ContextCompat.getColor(this, R.color.color_dark_background));
                }
            }
        } else {
            if (bitmap != null) {
                Palette.from(bitmap).generate(palette -> {
                    int defaultColor = ContextCompat.getColor(this, R.color.color_light_status_bar);
                    assert palette != null;
                    int color = palette.getDominantColor(defaultColor);
                    int newColor = ColorUtils.blendARGB(color, Color.BLACK, 0.5f);
                    imgMusicBackground.setBackgroundColor(newColor);
                    if (changeStatusBarColor) {
                        Tools.setStatusBarColor(MainActivity.this, rootView, newColor);
                    }
                });
            }
        }
    }

    public void changeSongName(String songName) {
        Constant.metadata = songName;
        txtMetadata.setText(songName);
        txtMetadataExpand.setText(songName);
    }

    public void changeAlbumArt(String artworkUrl) {
        Constant.albumArt = artworkUrl;
        setImageAlbumArt(artworkUrl, imgAlbumArtSmall);
        setImageAlbumArt(artworkUrl, imgAlbumArtLargePortrait);
        setImageAlbumArt(artworkUrl, imgAlbumArtLargeLandscape);
    }

    private void setImageAlbumArt(String artworkUrl, ImageView image) {
        Glide.with(getApplicationContext())
                .load(artworkUrl.replace(" ", "%20"))
                .placeholder(android.R.color.transparent)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .listener(new RequestListener<>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, @NonNull Target<Drawable> target, boolean isFirstResource) {
                        image.setVisibility(View.GONE);
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(@NonNull Drawable resource, @NonNull Object model, Target<Drawable> target, @NonNull DataSource dataSource, boolean isFirstResource) {
                        image.setVisibility(View.VISIBLE);
                        return false;
                    }
                })
                .into(image);
    }

    public void setIfPlaying() {
        if (RadioPlayerService.getInstance() != null) {
            RadioPlayerService.initialize(MainActivity.this);
            changePlayPause(RadioPlayerService.getInstance().isPlaying());
            seekBarUpdate();
        } else {
            changePlayPause(false);
        }
    }

    private final Runnable run = () -> {
        try {
            seekBarUpdate();
        } catch (Exception e) {
            Log.d(TAG, "printStackTrace error: " + e.getMessage());
            //e.printStackTrace();
        }
    };

    public void seekBarUpdate() {
        try {
            if (Constant.is_app_open) {
                seekBarSong.setProgress(Tools.getProgressPercentage(Constant.exoPlayer.getCurrentPosition(), Constant.exoPlayer.getDuration()));
                txtDuration.setText(Tools.milliSecondsToTimer(Constant.exoPlayer.getCurrentPosition()));
                txtTotalDuration.setText(Tools.milliSecondsToTimer(Constant.exoPlayer.getDuration()));
                seekBarSong.setSecondaryProgress(Constant.exoPlayer.getBufferedPercentage());
                if (RadioPlayerService.getInstance().isPlaying()) {
                    seekHandler.removeCallbacks(run);
                    seekHandler.postDelayed(run, 1000);
                }
            }
        } catch (Exception e) {
            Log.d(TAG, "printStackTrace error: " + e.getMessage());
            //e.printStackTrace();
        }
    }

    public void hideSeekBar() {
        lytSeekBar.setVisibility(View.GONE);
    }

    public void setBuffer(Boolean flag) {
        if (flag) {
            Constant.progressVisibility = true;
            progressBar.setVisibility(View.VISIBLE);

            lytPlayerExpand.setVisibility(View.VISIBLE);

            progressBarCollapse.setVisibility(View.VISIBLE);
            lytPlayCollapse.setVisibility(View.INVISIBLE);

            imgNext.setOnClickListener(null);
            imgNextExpand.setOnClickListener(null);

            imgPrevious.setOnClickListener(null);
            imgPreviousExpand.setOnClickListener(null);

            imgPlay.setOnClickListener(null);
            fabPlayExpand.setOnClickListener(null);
        } else {
            Constant.progressVisibility = false;
            progressBar.setVisibility(View.INVISIBLE);

            lytPlayerExpand.setVisibility(View.VISIBLE);

            progressBarCollapse.setVisibility(View.INVISIBLE);
            lytPlayCollapse.setVisibility(View.VISIBLE);

            imgNext.setOnClickListener(view -> togglePlayPosition(true));
            imgNextExpand.setOnClickListener(view -> togglePlayPosition(true));

            imgPrevious.setOnClickListener(view -> togglePlayPosition(false));
            imgPreviousExpand.setOnClickListener(view -> togglePlayPosition(false));

            imgPlay.setOnClickListener(view -> {
                if (!Tools.isConnect(this)) {
                    showSnackBar(getString(R.string.internet_not_connected));
                } else {
                    clickPlay(Constant.position);
                }
            });

            fabPlayExpand.setOnClickListener(view -> {
                if (!Tools.isConnect(this)) {
                    showSnackBar(getString(R.string.internet_not_connected));
                } else {
                    clickPlay(Constant.position);
                }
            });
        }
    }

    public void changeVolume() {
        final RelativePopupWindow popupWindow = new RelativePopupWindow(this);
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        assert inflater != null;
        @SuppressLint("InflateParams") View view = inflater.inflate(R.layout.lyt_volume, null);
        ImageView imageView1 = view.findViewById(R.id.img_volume_max);
        ImageView imageView2 = view.findViewById(R.id.img_volume_min);
        imageView1.setColorFilter(Color.BLACK);
        imageView2.setColorFilter(Color.BLACK);

        VerticalSeekBar seekBar = view.findViewById(R.id.seek_bar_volume);
        seekBar.getThumb().setColorFilter(sharedPref.getFirstColor(), PorterDuff.Mode.SRC_IN);
        seekBar.getProgressDrawable().setColorFilter(sharedPref.getSecondColor(), PorterDuff.Mode.SRC_IN);

        final AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        assert am != null;
        seekBar.setMax(am.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
        int volume_level = am.getStreamVolume(AudioManager.STREAM_MUSIC);
        seekBar.setProgress(volume_level);
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                am.setStreamVolume(AudioManager.STREAM_MUSIC, i, 0);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        popupWindow.setFocusable(true);
        popupWindow.setWidth(WindowManager.LayoutParams.WRAP_CONTENT);
        popupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        popupWindow.setContentView(view);
        popupWindow.showOnAnchor(imgVolume, RelativePopupWindow.VerticalPosition.ABOVE, RelativePopupWindow.HorizontalPosition.CENTER);
    }

    public void handleOnBackPressed() {
        onBackPressedDispatcher = getOnBackPressedDispatcher();
        onBackPressedDispatcher.addCallback(this, new OnBackPressedCallback(true) {
            @Override
            public void handleOnBackPressed() {
                if (slidingUpPanelLayout.getPanelState() == SlidingUpPanelLayout.PanelState.EXPANDED) {
                    slidingUpPanelLayout.setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED);
                } else if (fragmentManager.getBackStackEntryCount() != 0) {
                    Constant.isPausedFromClick = false;
                    getSupportFragmentManager().popBackStack();
                } else {
                    if (Config.ENABLE_RTL_MODE) {
                        if (viewPagerRTL.getCurrentItem() > 0) {
                            viewPagerRTL.setCurrentItem(0);
                        } else {
                            showExitDialog();
                        }
                    } else {
                        if (viewPager.getCurrentItem() > 0) {
                            viewPager.setCurrentItem(0);
                        } else {
                            showExitDialog();
                        }
                    }
                }
            }
        });
    }

    public void minimizeApp() {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    public void openCategoryDetail(String category_id, String category_name, String category_image, String radio_count) {
        FragmentCategoryDetail fragment = new FragmentCategoryDetail();
        Bundle args = new Bundle();
        args.putString("category_id", category_id);
        args.putString("category_name", category_name);
        args.putString("category_image", category_image);
        args.putString("radio_count", radio_count);
        fragment.setArguments(args);
        FragmentManager fragmentManager = getSupportFragmentManager();
        //FragmentTransaction transaction = fragmentManager.beginTransaction().setCustomAnimations(R.anim.slide_in, R.anim.fade_out, R.anim.fade_in, R.anim.slide_out);
        FragmentTransaction transaction = fragmentManager.beginTransaction().setCustomAnimations(R.animator.slide_up, 0, 0, R.animator.slide_down);
        transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
        transaction.add(R.id.fragment_container, fragment).addToBackStack("category_detail");
        transaction.commit();
    }

    public void openFragmentSearch() {
        FragmentSearch fragment = new FragmentSearch();
        FragmentManager fragmentManager = getSupportFragmentManager();
        //FragmentTransaction transaction = fragmentManager.beginTransaction().setCustomAnimations(R.anim.slide_in, R.anim.fade_out, R.anim.fade_in, R.anim.slide_out);
        FragmentTransaction transaction = fragmentManager.beginTransaction().setCustomAnimations(R.animator.slide_up, 0, 0, R.animator.slide_down);
        transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
        transaction.add(R.id.fragment_container, fragment).addToBackStack("search");
        transaction.commit();
    }

    public void openFragmentSettings() {
        FragmentSettings fragment = new FragmentSettings();
        FragmentManager fragmentManager = getSupportFragmentManager();
        //FragmentTransaction transaction = fragmentManager.beginTransaction().setCustomAnimations(R.anim.slide_in, R.anim.fade_out, R.anim.fade_in, R.anim.slide_out);
        FragmentTransaction transaction = fragmentManager.beginTransaction().setCustomAnimations(R.animator.slide_up, 0, 0, R.animator.slide_down);
        transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
        transaction.add(R.id.root_view, fragment).addToBackStack("settings");
        transaction.commit();
    }

    private boolean isServiceRunning() {
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        assert manager != null;
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (RadioPlayerService.class.getName().equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }

    public void hideKeyboard() {
        try {
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
            if (((getCurrentFocus() != null) && ((getCurrentFocus().getWindowToken() != null)))) {
                ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
            }
        } catch (Exception e) {
            Log.d(TAG, "printStackTrace error: " + e.getMessage());
            //e.printStackTrace();
        }
    }

    public void themeColor() {
        if (sharedPref.getIsDarkTheme()) {
            lytBackground.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.color_dark_background));
            lytCollapse.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.color_dark_background));
            imgCollapse.setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.color_white), PorterDuff.Mode.SRC_IN);
            imgVolume.setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.color_white), PorterDuff.Mode.SRC_IN);
            imgTimer.setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.color_white), PorterDuff.Mode.SRC_IN);
            imgFavorite.setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.color_white), PorterDuff.Mode.SRC_IN);
            imgShare.setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.color_white), PorterDuff.Mode.SRC_IN);
            cardMiniPlayer.setCardBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.color_dark_mini_player_background));
            cardMiniPlayer.setStrokeColor(ContextCompat.getColor(getApplicationContext(), R.color.color_dark_icon));
            imgPrevious.setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.color_white), PorterDuff.Mode.SRC_IN);
            imgPreviousExpand.setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.color_white), PorterDuff.Mode.SRC_IN);
            imgNext.setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.color_white), PorterDuff.Mode.SRC_IN);
            imgNextExpand.setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.color_white), PorterDuff.Mode.SRC_IN);
            imgPlay.setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.color_white), PorterDuff.Mode.SRC_IN);
            bgLine.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.color_white));
            if (isFirstTime) {
                isFirstTime = false;
                Tools.darkNavigation(this);
            }
        } else {
            lytBackground.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.color_light_background));
            lytCollapse.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.color_white));
            imgCollapse.setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.color_white), PorterDuff.Mode.SRC_IN);
            imgVolume.setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.color_white), PorterDuff.Mode.SRC_IN);
            imgTimer.setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.color_white), PorterDuff.Mode.SRC_IN);
            imgFavorite.setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.color_white), PorterDuff.Mode.SRC_IN);
            imgShare.setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.color_white), PorterDuff.Mode.SRC_IN);
            cardMiniPlayer.setCardBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.color_light_mini_player_background));
            cardMiniPlayer.setStrokeColor(ContextCompat.getColor(getApplicationContext(), R.color.color_light_icon));
            imgPrevious.setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.color_light_icon), PorterDuff.Mode.SRC_IN);
            imgPreviousExpand.setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.color_white), PorterDuff.Mode.SRC_IN);
            imgNext.setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.color_light_icon), PorterDuff.Mode.SRC_IN);
            imgNextExpand.setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.color_white), PorterDuff.Mode.SRC_IN);
            imgPlay.setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.color_light_icon), PorterDuff.Mode.SRC_IN);
            bgLine.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.color_white));
            if (isFirstTime) {
                isFirstTime = false;
                Tools.lightNavigation(this);
            }
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        Tools.postDelayed(() -> {
            if (Constant.isPausedFromClick && Constant.isForeground) {
                stopRadioServices(Constant.position);
            }
        }, 1000);
    }

    @Override
    public void onResume() {
        super.onResume();
        initComponent();
        themeColor();
        adsManager.resumeBannerAd(Config.BANNER_HOME);
        Tools.postDelayed(() -> {
            if (Constant.isPausedFromClick && Constant.isForeground) {
                startRadioServices(sharedPref.getCurrentRadioPosition());
                Constant.isPausedFromClick = false;
            }
        }, 1000);
    }

    @Override
    protected void onDestroy() {
        Constant.is_app_open = false;
        Constant.isPausedFromClick = false;
        Constant.isRadioPlaying = false;
        adsManager.destroyBannerAd();
        destroyAppOpenAd();
        super.onDestroy();
    }

    public void destroyAppOpenAd() {
        AppOpenAd.isAppOpenAdLoaded = false;
        if (Config.FORCE_TO_SHOW_APP_OPEN_AD_ON_START) {
            adsManager.destroyAppOpenAd();
            ProcessLifecycleOwner.get().getLifecycle().removeObserver(this);
        }
    }

    @Override
    public AssetManager getAssets() {
        return getResources().getAssets();
    }

    public void startRadioServices(int position) {
        Intent intent = new Intent(MainActivity.this, RadioPlayerService.class);
        RadioPlayerService.createInstance().initializeRadio(MainActivity.this, Constant.item_radio.get(position));
        intent.setAction(RadioPlayerService.ACTION_PLAY);
        startService(intent);
    }

    public void stopRadioServices(int position) {
        Intent intent = new Intent(MainActivity.this, RadioPlayerService.class);
        RadioPlayerService.createInstance().initializeRadio(MainActivity.this, Constant.item_radio.get(position));
        intent.setAction(RadioPlayerService.ACTION_STOP);
        startService(intent);
    }

    private void inAppReview() {
        if (sharedPref.getInAppReviewToken() <= 3) {
            sharedPref.updateInAppReviewToken(sharedPref.getInAppReviewToken() + 1);
            Log.d(TAG, "in app update token");
        } else {
            ReviewManager manager = ReviewManagerFactory.create(this);
            Task<ReviewInfo> request = manager.requestReviewFlow();
            request.addOnCompleteListener(task -> {
                if (task.isSuccessful()) {
                    ReviewInfo reviewInfo = task.getResult();
                    manager.launchReviewFlow(MainActivity.this, reviewInfo).addOnFailureListener(e -> {
                    }).addOnCompleteListener(complete -> Log.d(TAG, "Success")
                    ).addOnFailureListener(failure -> Log.d(TAG, "Rating Failed"));
                }
            }).addOnFailureListener(failure -> Log.d(TAG, "In-App Request Failed " + failure));
            Log.d(TAG, "in app token complete, show in app review if available");
        }
        Log.d(TAG, "in app review token : " + sharedPref.getInAppReviewToken());
    }

    private void inAppUpdate() {
        Task<AppUpdateInfo> appUpdateInfoTask = appUpdateManager.getAppUpdateInfo();
        appUpdateInfoTask.addOnSuccessListener(appUpdateInfo -> {
            if (appUpdateInfo.updateAvailability() == UpdateAvailability.UPDATE_AVAILABLE
                    && appUpdateInfo.isUpdateTypeAllowed(AppUpdateType.IMMEDIATE)) {
                startUpdateFlow(appUpdateInfo);
            } else if (appUpdateInfo.updateAvailability() == UpdateAvailability.DEVELOPER_TRIGGERED_UPDATE_IN_PROGRESS) {
                startUpdateFlow(appUpdateInfo);
            }
        });
    }

    @SuppressWarnings("deprecation")
    private void startUpdateFlow(AppUpdateInfo appUpdateInfo) {
        try {
            appUpdateManager.startUpdateFlowForResult(appUpdateInfo, AppUpdateType.IMMEDIATE, this, Constant.IMMEDIATE_APP_UPDATE_REQ_CODE);
        } catch (IntentSender.SendIntentException e) {
            Log.d(TAG, "printStackTrace error: " + e.getMessage());
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constant.IMMEDIATE_APP_UPDATE_REQ_CODE) {
            if (resultCode == RESULT_CANCELED) {
                showSnackBar(getString(R.string.msg_cancel_update));
            } else if (resultCode == RESULT_OK) {
                showSnackBar(getString(R.string.msg_success_update));
            } else {
                showSnackBar(getString(R.string.msg_failed_update));
                inAppUpdate();
            }
        }
    }

    public void selectRadio() {
        if (Config.ENABLE_RTL_MODE) {
            viewPagerRTL.setCurrentItem(1);
        } else {
            viewPager.setCurrentItem(1);
        }
    }

    public void selectCategory() {
        if (Config.ENABLE_RTL_MODE) {
            viewPagerRTL.setCurrentItem(2);
        } else {
            viewPager.setCurrentItem(2);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        if (sharedPref.getIsDarkTheme()) {
            Tools.tintMenuIcon(this, menu.findItem(R.id.search), R.color.color_white);
            Tools.tintMenuIcon(this, menu.findItem(R.id.settings), R.color.color_white);
        } else {
            if (Config.ENABLE_NEW_UI) {
                Tools.tintMenuIcon(this, menu.findItem(R.id.search), R.color.color_light_icon);
                Tools.tintMenuIcon(this, menu.findItem(R.id.settings), R.color.color_light_icon);
            } else {
                Tools.tintMenuIcon(this, menu.findItem(R.id.search), R.color.color_white);
                Tools.tintMenuIcon(this, menu.findItem(R.id.settings), R.color.color_white);
            }
        }
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem menuItem) {
        if (menuItem.getItemId() == R.id.search) {
            openFragmentSearch();
            return true;
        } else if (menuItem.getItemId() == R.id.settings) {
            openFragmentSettings();
            return true;
        }
        return super.onOptionsItemSelected(menuItem);
    }

    public void showBottomSheet(Radio radio) {
        tools.showBottomSheetDialog(this, parentView, radio);
    }

    public void showSnackBar(String msg) {
        Snackbar.make(parentView, msg, Snackbar.LENGTH_SHORT).show();
    }

    public void onItemRadioClick(final ArrayList<Radio> radios, int position) {
        Constant.item_radio.clear();
        Constant.item_radio.addAll(radios);
        Constant.position = position;
        sharedPref.setCurrentRadioPosition(position);
        Constant.isPausedFromClick = true;
        showInterstitialAd();
        Tools.postDelayed(() -> {
            hideSeekBar();
            if (Config.OPEN_PLAYER_WHEN_RADIO_LIST_CLICKED) {
                if (slidingUpPanelLayout.getPanelState() == SlidingUpPanelLayout.PanelState.COLLAPSED) {
                    slidingUpPanelLayout.setPanelState(SlidingUpPanelLayout.PanelState.EXPANDED);
                }
            }
            Tools.postDelayed(() -> {
                updatePlayerView(radios.get(position).radio_name, radios.get(position).category_name, sharedPref.getBaseUrl() + "/upload/" + radios.get(position).radio_image);
                startRadioServices(position);
                hideSeekBar();
            }, 300);
        }, 100);
    }

    public void updatePlayerView(String radioName, String metaData, String radioImage) {
        txtRadioName.setText(radioName);
        txtRadioNameExpand.setText(radioName);

        txtMetadata.setText(metaData);
        txtMetadataExpand.setText(metaData);

        Glide.with(getApplicationContext())
                .asBitmap()
                .load(radioImage.replace(" ", "%20"))
                .placeholder(R.drawable.ic_artwork)
                .into(new CustomTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap bitmap, @Nullable Transition<? super Bitmap> transition) {
                        imgRadioSmall.setImageBitmap(bitmap);
                        imgRadioLargePortrait.setImageBitmap(bitmap);
                        imgRadioLargeLandscape.setImageBitmap(bitmap);
                        showBlurBackgroundImage(bitmap);

                        DisplayMetrics displayMetrics = new DisplayMetrics();
                        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
                        Bitmap newBitmap = PaletteUtils.getDominantGradient(bitmap, displayMetrics.heightPixels, displayMetrics.widthPixels);
                        changePlayerBackground(newBitmap, Constant.isPlayerExpanded);
                        Constant.colorBitmap = newBitmap;

                    }

                    @Override
                    public void onLoadCleared(@Nullable Drawable placeholder) {

                    }
                });
        imgAlbumArtSmall.setVisibility(View.GONE);
        imgAlbumArtLargePortrait.setVisibility(View.GONE);
        imgAlbumArtLargeLandscape.setVisibility(View.GONE);
    }

    public void updateView(String id) {
        ApiInterface apiInterface = RestAdapter.createAPI(sharedPref.getBaseUrl());
        Call<Value> call = apiInterface.updateView(id);
        call.enqueue(new Callback<>() {
            @Override
            public void onResponse(@NonNull Call<Value> call, @NonNull Response<Value> response) {
                Value data = response.body();
                if (data != null) {
                    Log.d(TAG, "View counter updated +" + data.value);
                }
            }

            @Override
            public void onFailure(@NonNull Call<Value> call, @NonNull Throwable t) {
                Log.d(TAG, "error " + t.getMessage());
            }
        });
    }

    public static AlertDialog alertDialog = null;

    @SuppressLint("InflateParams")
    private void showExitDialog() {
        showBannerAd(false);
        View view;
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            view = getLayoutInflater().inflate(R.layout.dialog_exit_landscape, null);
        } else {
            view = getLayoutInflater().inflate(R.layout.dialog_exit_portrait, null);
        }

        final MaterialAlertDialogBuilder alert = new MaterialAlertDialogBuilder(this);
        alert.setView(view);

        FloatingActionButton btnRate = view.findViewById(R.id.btn_rate);
        FloatingActionButton btnShare = view.findViewById(R.id.btn_share);

        LinearLayout nativeAdView = view.findViewById(R.id.native_ad_view);
        Tools.setNativeAdStyle(MainActivity.this, nativeAdView, Config.NATIVE_AD_STYLE_EXIT_DIALOG);
        adsManager.loadNativeAdView(view, Config.NATIVE_AD_STYLE_EXIT_DIALOG, Config.NATIVE_AD_EXIT_DIALOG);

        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            nativeAdView.setVisibility(View.GONE);
        } else {
            nativeAdView.setVisibility(View.VISIBLE);
        }

        alertDialog = alert.create();
        Tools.dialogExitButtonSelected(this, view, alertDialog, () -> {
            finish();
            adsManager.destroyBannerAd();
            if (isServiceRunning()) {
                Intent stop = new Intent(this, RadioPlayerService.class);
                stop.setAction(RadioPlayerService.ACTION_STOP);
                startService(stop);
                Log.d("RADIO_SERVICE", "Service Running");
            } else {
                Log.d("RADIO_SERVICE", "Service Not Running");
            }
        }, this::minimizeApp);

        btnRate.setOnClickListener(v -> {
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + BuildConfig.APPLICATION_ID)));
            alertDialog.dismiss();
        });

        btnShare.setOnClickListener(v -> {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_SEND);
            intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.app_name));
            intent.putExtra(Intent.EXTRA_TEXT, getString(R.string.share_content) + "\n" + "https://play.google.com/store/apps/details?id=" + BuildConfig.APPLICATION_ID);
            intent.setType("text/plain");
            startActivity(intent);
            alertDialog.dismiss();
        });

        alertDialog.setOnDismissListener(dialogInterface -> showBannerAd(true));
        alertDialog.show();
    }

    private void startTimer(long minutes) {
        setCountDownTimer(minutes * 60);
        showCountDownTimer(true);
        mCountDownTimer.start();
    }

    private void stopTimer() {
        mCountDownTimer.cancel();
        showCountDownTimer(false);
        txtTimer.setText("00:00:00");
    }

    private void setCountDownTimer(long seconds) {
        mCountDownTimer = new CountDownTimer(seconds * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                txtTimer.setText(Tools.formatSeconds(millisUntilFinished / 1000));
                if (millisUntilFinished > 0) {
                    showCountDownTimer(true);
                } else {
                    showCountDownTimer(false);
                }
                Log.d(TAG, "seconds remaining: " + millisUntilFinished / 1000);
            }

            @Override
            public void onFinish() {
                txtTimer.setText("00:00:00");
                showCountDownTimer(false);
                if (isServiceRunning()) {
                    Intent stop = new Intent(MainActivity.this, RadioPlayerService.class);
                    stop.setAction(RadioPlayerService.ACTION_STOP);
                    startService(stop);
                }
            }
        };
    }

    private void showCountDownTimer(boolean show) {
        if (show) {
            imgTimer.setVisibility(View.GONE);
            imgTimerStop.setVisibility(View.VISIBLE);
            txtTimer.setVisibility(View.VISIBLE);
        } else {
            imgTimer.setVisibility(View.VISIBLE);
            imgTimerStop.setVisibility(View.GONE);
            txtTimer.setVisibility(View.GONE);
        }
    }

    @SuppressWarnings("ConstantValue")
    private void showBottomNavigation(boolean show) {
        if (Config.NAVIGATION_TYPE == NavigationType.BOTTOM_NAVIGATION) {
            if (show) {
                tabLayout.setVisibility(View.VISIBLE);
            } else {
                tabLayout.setVisibility(View.GONE);
            }
        }
    }

    private void showBannerAd(boolean show) {
        if (show) {
            lytBannerAd.setVisibility(View.VISIBLE);
        } else {
            lytBannerAd.setVisibility(View.GONE);
        }
    }

    public void goToFirstPage() {
        if (Config.ENABLE_RTL_MODE) {
            viewPagerRTL.setCurrentItem(0);
        } else {
            viewPager.setCurrentItem(0);
        }
    }

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        isPortrait(newConfig.orientation != Configuration.ORIENTATION_LANDSCAPE);
        if (alertDialog != null) {
            alertDialog.dismiss();
            Log.d(TAG, "alert dialog dismiss");
        } else {
            Log.d(TAG, "alert dialog null");
        }
    }

    private void isPortrait(boolean isPortrait) {
        if (isPortrait) {
            lytCoverImagePortrait.setVisibility(View.VISIBLE);
            lytCoverImageLandscape.setVisibility(View.GONE);
        } else {
            lytCoverImagePortrait.setVisibility(View.GONE);
            lytCoverImageLandscape.setVisibility(View.VISIBLE);
        }
    }

}